<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BScreenAppStore
 *
 * @author I062261
 */
class BScreenAppStore extends BUIScreen {

    //put your code here

    public function render($data = null) {
        //parent::render($data);
        $model = new AddServiceAppFormModel();

        if (isset($_POST['AddServiceAppFormModel'])) {
            $model->attributes = $_POST['AddServiceAppFormModel'];
        }

        $apps = $this->getServiceAppsData();
        foreach ($apps as $id => $name) {
            if ($this->isAjaxLinkClicked('addApp' . $id)) {
                $this->addServiceApps(array($id));
                $this->gotoUINode(
                        Blyn::app()->getActiveService()->getId(),  
                        Blyn::app()->getActiveServiceApp()->getId(), 
                        Blyn::app()->getActiveOperation()->getId());
            }
        }

        $this->addRenderView('appStore', 'appStoreView', array('model' => $model));
    }

    public function getServiceAppsData() {

        $service = Blyn::app()->getActiveService();

        $db = Blyn::app()->getAppDb();

        $apps = $db->getVisibleServiceApps($service);

        $myApps = Blyn::app()->getActiveService()->getServiceApps();

        $ids = array();

        foreach ($apps as $app) {
            array_push($ids, $app->getId());
        }

        foreach ($myApps as $app) {
            $appId = $app->getId();
            if (in_array($appId, $ids)) {
                unset($apps[$appId]);
            }
        }

        $data = array();

        foreach ($apps as $app) {
            if ($app->isVisible($service)) {
                $data[$app->getId()] = $app->getName();
            }
        }
        return $data;
    }

    public function addServiceApps($sApps) {
        $serviceId = Blyn::app()->getActiveService()->getId();

        foreach ($sApps as $appId) {
            $result = Blyn::app()->getActiveServiceApp()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $serviceId, 'App' => $appId));
        }
    }

}

?>
